package com.sakuracard.stepdemo.web.controller.base;

import com.sakuracard.stepdemo.mapper.BaseMapper;
import com.sakuracard.stepdemo.model.AFieldEntity;
import com.sakuracard.stepdemo.model.base.TransferableBaseEntity;
import com.sakuracard.stepdemo.service.base.BaseService;
import com.sakuracard.stepdemo.web.model.ListResult;
import com.sakuracard.stepdemo.web.model.OperatorResult;
import com.sakuracard.stepdemo.web.model.ResponseResult;
import com.sakuracard.stepdemo.web.model.SearchParams;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

public class BaseController<SERVICE extends BaseService<ENTITY>, ENTITY extends TransferableBaseEntity, CONDITION extends SearchParams> {
  protected SERVICE baseService;

  @GetMapping("")
  public ResponseResult<ListResult<ENTITY>> getList(CONDITION params) {
    params.initDefaults();
    return ResponseResult.success(this.baseService.getList(params));
  }

  @GetMapping("/getAFields")
  public ResponseResult<AFieldEntity> getAFields() {
    List<AFieldEntity.KeyWordItem> keyWords = new ArrayList<>();
    keyWords.add(new AFieldEntity.KeyWordItem("title", "名称"));
    keyWords.add(new AFieldEntity.KeyWordItem("status", "状态"));

    var field = new AFieldEntity();
    field.setGetKeyWords(keyWords);
    return ResponseResult.success(field);
  }

  @GetMapping("/{id}")
  public ResponseResult<?> getData(@PathVariable int id) {
    ENTITY o = this.baseService.getData(id);
    return ResponseResult.success(o);
  }

  @PostMapping("")
  public ResponseResult<?> insertData(@ModelAttribute ENTITY entity) {
    boolean result = this.baseService.insertData(entity);
    if (!result) {
      return ResponseResult.fail();
    }
    return ResponseResult.success(new OperatorResult<Integer>(entity.getId()));
  }

  @PutMapping(path = "/{id}")
  public ResponseResult<?> updateData(@PathVariable("id") int id, @ModelAttribute ENTITY entity) {
    boolean result = baseService.updateData(id, entity);
    return ResponseResult.success(new OperatorResult<Integer>(id));
  }
}
